import React, {useEffect, useState} from 'react';
import { Card, Col, Row, Button, Tag, message } from 'antd';
import axios from 'axios';
import { Navigate, useNavigate } from "react-router-dom";

import {
  Link,
} from "react-router-dom";

import { API_HOST } from './Util.jsx'

const Hall = () => {

  const [messageApi, contextHolder] = message.useMessage();
  const [rooms, setRooms] = useState([])
  const navigate=useNavigate()

  const createNewGame = ()=>{
    let userInfo = JSON.parse(localStorage.getItem('card_player'))
    
    if (!userInfo){
      console.log('createNewGame: userInfo', userInfo)
      location.reload()
      // useNavigate(...)
    }

    axios.post(API_HOST()+'/api/room', userInfo).then((res)=>{
      console.log(res.data)
      messageApi.open({
        type: 'success',
        content: '创建成功',
      });

      let roomId = res.data.Id
      navigate('/room/'+roomId)


    }).catch((err)=>{
      console.log(err)
    })
  }

  useEffect(()=>{
    axios.get(API_HOST()+'/api/rooms').then((res)=>{
      console.log(res.data)
      setRooms(res.data)
    })
  }, [])

  return (
    <>
      {contextHolder}
        <Row gutter={16}>
          {
          rooms.map((room, idx)=>
          <Col span={8} key={idx}>
            <Card title={`Room:${room.Id}`} bordered={true} style={{'width':'100%', 'height': '200px', 'margin': '15px'}}>
              <Tag>{room.State}</Tag>
              <p>{room.OwnerId}</p>
              <Button onClick={()=>navigate(`/room/${room.Id}`)}>进入房间</Button>
            </Card>
          </Col>
          )}
          <Col span={8}>
            <Button type="dashed" style={{'width':'100%', 'height': '200px', 'margin': '15px'}} onClick={createNewGame} >
              创建
            </Button>
          </Col>
        </Row>

    </>
  );
};

export default Hall;
